package com.mind.adjust.task;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mind.adjust.mapper.AjRuleCheckMapper;
import com.mind.common.utils.DateUtils;
import com.mind.customer.mapper.AjRuleMapper;
import com.mind.system.domain.AjRule;
import com.mind.system.domain.AjRuleCheck;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("ruleActiveTask")
@Log4j2
public class RuleActiveTask {
    @Resource
    private AjRuleCheckMapper ruleCheckMapper;

    @Resource
    private AjRuleMapper ruleMapper;
    // 规则激活任务
    public void ruleActive() {
        log.info("规则激活任务开始...");
        // 查出需要激活的任务
        List<AjRuleCheck> ajRuleChecks = ruleCheckMapper.selectList(new QueryWrapper<>(new AjRuleCheck() {{
            setStatus("3");
            setIsActive(0);
        }}));
        log.info("规则激活任务数量:{}", ajRuleChecks.size());
        for(AjRuleCheck ajRuleCheck : ajRuleChecks) {
            log.info("规则激活任务:{}", JSON.toJSONString(ajRuleCheck));
            if(ajRuleCheck.getActiveDate() != null && DateUtils.isToday(DateUtils.parseDateToStr("yyyy-MM-dd", ajRuleCheck.getActiveDate()))){
                if(ajRuleCheck.getNewRuleId() != null) {
                    ruleMapper.updateById(new AjRule(){{
                        setId(ajRuleCheck.getNewRuleId());
                        setStatus("1");
                    }});
                    ruleMapper.updateById(new AjRule(){{
                        setId(ajRuleCheck.getRuleId());
                        setExpireDate(DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd", DateUtils.addDays(new Date(), -1))));
                        setStatus("2");
                    }});
                }else{
                    ruleMapper.updateById(new AjRule(){{
                        setId(ajRuleCheck.getRuleId());
                        setStatus("1");
                    }});
                }
                ruleCheckMapper.updateById(new AjRuleCheck(){{
                    setId(ajRuleCheck.getId());
                    setIsActive(1);
                }});
            }
        }
        log.info("规则激活任务结束...");

    }
}
